package com.lap.auth.application.dict;

import com.lap.auth.application.dict.assembler.DictAssembler;
import com.lap.auth.application.dict.command.BatchCreateDictCmd;
import com.lap.auth.application.dict.dto.DictDto;
import com.lap.auth.domain.dict.Dict;
import com.lap.auth.domain.dict.repository.DictRepository;
import com.lap.i18n.starter.entity.LocalInfo;
import com.lap.i18n.starter.helper.LangHelper;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@RequiredArgsConstructor
@Service
public class DictAppService {

  private final DictAssembler dictAssembler;
  private final DictRepository dictRepository;

  @Transactional(rollbackFor = Exception.class)
  public void batchCreateDict(BatchCreateDictCmd cmd) {
    List<Dict> list = dictAssembler.toDomains(cmd);
    dictRepository.deleteByDictTypeCode(cmd.getDictTypeCode());
    dictRepository.saveAll(list);
  }

  public List<DictDto> getDictList(String dictTypeCode) {
    List<Dict> sources = dictRepository.findByDictTypeCode(dictTypeCode);
    return dictAssembler.toDtoList(sources);
  }

  public Map<String, List<DictDto>> queryDictList(List<String> dictTypeCodes) {
    LocalInfo info = LangHelper.get();
    log.info("localInfo:{}", LangHelper.get());
    List<Dict> sources = dictRepository.findByDictTypeCode(dictTypeCodes, info.storeLang());
    List<DictDto> list = dictAssembler.toDtoList(sources);
    return list.stream()
        .collect(
            Collectors.groupingBy(
                DictDto::getDictTypeCode,
                Collectors.collectingAndThen(
                    Collectors.toList(),
                    dto ->
                        dto.stream()
                            .sorted(Comparator.comparingInt(DictDto::getSortOrder))
                            .toList())));
  }
}
